package main

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

type LoginForm struct {
	User           string    `form:"user" json:"user" binding:"required"`
	Password       string    `form:"password" json:"pwd" binding:"required"`
	FirstLoginTime time.Time `form:"first_login_time" json:"firstLoginTime" time_format:"2006-01-02" time_utc:"1"`
}

func main() {
	router := gin.Default()
	router.POST("/login", func(ctx *gin.Context) {
		// 你可以使用显式绑定声明绑定 multipart form：
		// 根据 Content-Type Header 推断使用哪个绑定器
		// c.ShouldBindWith(&form, binding.Form)
		// 或者简单地使用 ShouldBind 方法自动绑定：
		var form LoginForm
		// can bing get query params or post
		// use ShouldBind is ok
		// 但是只能调用一次，第二次调用就会报错
		err := ctx.ShouldBind(&form)
		if err == nil {
			if form.User == "user" && form.Password == "test@123" {
				ctx.JSON(http.StatusOK, gin.H{"status": "login success"})
			} else {
				ctx.JSON(http.StatusBadRequest, gin.H{"message": "user or password invalid"})
			}
		} else {
			ctx.JSON(http.StatusBadGateway, gin.H{"message": err.Error()})
		}
	})

	// login with json
	router.POST("/login/json", func(ctx *gin.Context) {
		var form LoginForm
		err := ctx.BindJSON(&form)
		if err == nil {
			if form.User == "user" && form.Password == "test@123" {
				log.Println("firstLoginTime=", form.FirstLoginTime.String())
				ctx.JSON(http.StatusOK, gin.H{"status": "login success"})
			} else {
				ctx.JSON(http.StatusBadRequest, gin.H{"message": "user or password invalid"})
			}
		} else {
			ctx.JSON(http.StatusBadGateway, gin.H{"message": err.Error()})
		}
	})

	router.Run(":8080")
}
